package ai.people.core.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author yuanqinglong
 * @date 2022/3/1 16:21
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    /**
     * 应用程序上下文
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }


    /**
     * 让应用程序上下文
     *
     * @return {@link ApplicationContext}
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过类型获取Bean
     *
     * @param clazz clazz
     * @return {@link T}
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过类型和名称获取Bean
     *
     * @param clazz    clazz
     * @param beanName bean名字
     * @return {@link T}
     */
    public static <T> T getBean(Class<T> clazz, String beanName) {
        return applicationContext.getBean(clazz, beanName);
    }

    /**
     * 通过名称获取Bean
     *
     * @param beanName bean名字
     * @return {@link Object}
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

}
